/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Entities;

import constants.Consts;
import helpers.Debug;
import java.io.Serializable;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 * @author Bari
 */
@Entity
@Table(name = "resources")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Resource.findAll", query = "SELECT r FROM Resource r"),
    @NamedQuery(name = "Resource.findById", query = "SELECT r FROM Resource r WHERE r.id = :id"),
    @NamedQuery(name = "Resource.findByCategoryId", query = "SELECT r FROM Resource r WHERE r.categoryid.id = :categoryid"),
    @NamedQuery(name = "Resource.findByDescription", query = "SELECT r FROM Resource r WHERE r.description = :description"),
    @NamedQuery(name = "Resource.findByName", query = "SELECT r FROM Resource r WHERE r.name = :name"),
    @NamedQuery(name = "Resource.findByTelnumber", query = "SELECT r FROM Resource r WHERE r.telnumber = :telnumber")})
public class Resource extends AbstractJsonMaterial implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Long id;
    @Size(max = 255)
    @Column(name = "description")
    private String description;
    @Size(max = 255)
    @Column(name = "name")
    private String name;
    @Size(max = 255)
    @Column(name = "telnumber")
    private String telnumber;
    @JoinColumn(name = "categoryid", referencedColumnName = "id")
    @ManyToOne
    private Resourcecategory categoryid;
    @OneToMany(mappedBy = "rid")
    private Collection<ReservationLogs> reservationLogsCollection;
    @OneToMany(mappedBy = "resourceid")
    private Collection<Activereservation> activereservationCollection;

    public Resource() {
    }

    public Resource(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTelnumber() {
        return telnumber;
    }

    public void setTelnumber(String telnumber) {
        this.telnumber = telnumber;
    }

    public Resourcecategory getCategory() {
        return categoryid;
    }

    public void setCategory(Resourcecategory categoryid) {
        this.categoryid = categoryid;
    }

    @XmlTransient
    public Collection<ReservationLogs> getReservationLogsCollection() {
        return reservationLogsCollection;
    }

    public void setReservationLogsCollection(Collection<ReservationLogs> reservationLogsCollection) {
        this.reservationLogsCollection = reservationLogsCollection;
    }

    @XmlTransient
    public Collection<Activereservation> getActivereservationCollection() {
        return activereservationCollection;
    }

    public void setActivereservationCollection(Collection<Activereservation> activereservationCollection) {
        this.activereservationCollection = activereservationCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Resource)) {
            return false;
        }
        Resource other = (Resource) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Entities.Resources[ id=" + id + " ]";
    }

    @Override
    public JSONObject toJson() {
       try {
            JSONObject json=new JSONObject();
            json.put(Consts.RESOURCE_ID, id);
            json.put(Consts.RESOURCE_NAME, name);
            json.put(Consts.RESOURCE_DESCRIPTION, description);
            
            if (activereservationCollection.size()>0)
            {
                json.put(Consts.RESOURCE_STATE, Consts.RESOURCE_ACTIVE);
                String userId= activereservationCollection.iterator().next().getUser().getIdentifier();
                json.put(Consts.USER_ID,userId);
            }
            else
            {
                json.put(Consts.RESOURCE_STATE, Consts.RESOURCE_NOT_ACTIVE);
            }
            return json;
        } catch (JSONException ex) {
            Logger.getLogger(Resource.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    
    public JSONObject toJsonWithOwnershipCheck(User client) {
       try {
            JSONObject json=new JSONObject();
            json.put(Consts.RESOURCE_ID, id);
            json.put(Consts.RESOURCE_NAME, name);
            json.put(Consts.RESOURCE_DESCRIPTION, description);
            
            if (activereservationCollection.size()>0)
            {
             //   Debug.logMessage("toJsonWithOwnershipCheck", name+" reservationCount:"+activereservationCollection.size());
                json.put(Consts.RESOURCE_STATE, Consts.RESOURCE_ACTIVE);
                User resourceOwner= activereservationCollection.iterator().next().getUser();
                if (resourceOwner.equals(client))
                {
                    json.put(Consts.RESOURCE_OWNERSHIP, Consts.RESOURCE_OWNER);
                }
                else
                {
                    json.put(Consts.RESOURCE_OWNERSHIP, Consts.RESOURCE_NOT_OWNER);
                }
            }
            else
            {
                json.put(Consts.RESOURCE_STATE, Consts.RESOURCE_NOT_ACTIVE);
            }
            return json;
        } catch (JSONException ex) {
            Logger.getLogger(Resource.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    
}
